package com.neusoft.SPNursingHome.service;// src/main/java/com/neusoft/SPNursingHome/service/impl/BedRecordServiceImpl.java

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.SPNursingHome.dao.BedDao;
import com.neusoft.SPNursingHome.dao.BedRecordDao;
import com.neusoft.SPNursingHome.dao.ClientDao;
import com.neusoft.SPNursingHome.po.*;
import com.neusoft.SPNursingHome.service.BedRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class BedRecordServiceImpl implements BedRecordService {

    @Autowired
    private BedRecordDao dao;
    @Autowired
    private BedDao bedDao;
    @Autowired
    private ClientDao clientDao;

    @Override
    public ResponseBean<List<BedRecord>> listAll() {
        List<BedRecord> list = dao.selectList(new QueryWrapper<>());
        return new ResponseBean<>(list);
    }

    @Override
    public ResponseBean<IPage<BedRecord>> listPage(long page, long size) {
        Page<BedRecord> pager = new Page<>(page, size);
        IPage<BedRecord> pageData = dao.selectPage(pager, new QueryWrapper<>());
        return new ResponseBean<>(pageData);
    }

    @Override
    public ResponseBean<BedRecord> getById(Integer id) {
        BedRecord rec = dao.selectById(id);
        if (rec == null) {
            return new ResponseBean<>(404, "未找到对应 BedRecord");
        }
        return new ResponseBean<>(rec);
    }

    @Override
    public ResponseBean<Void> create(BedRecord record) {
        int rows = dao.insert(record);
        if (rows != 1) {
            return new ResponseBean<>(500, "新增 BedRecord 失败");
        }
        return new ResponseBean<>();
    }

    @Override
    public ResponseBean<Void> update(BedRecord record) {
        System.out.println(">>> record = " + record);
        int rows = dao.updateById(record);
        System.out.println(">>> update rows = " + rows);
        if (rows != 1) {
            System.out.println(">>> 更新失败");
            return new ResponseBean<>(500, "更新 BedRecord 失败");
        }
        System.out.println(">>> 更新成功");
        return new ResponseBean<>(200, "床位更新成功");
    }


    @Override
    public ResponseBean<Void> deleteById(Integer id) {
        int rows = dao.deleteById(id);
        if (rows != 1) {
            return new ResponseBean<>(500, "删除 BedRecord 失败");
        }
        return new ResponseBean<>();
    }

    @Override
    public ResponseBean<IPage<BedRecordWithClient>> listWithClientByCondition(
            String clientName,
            Date beginTime,
            Date endTime,
            Integer bedRecordStatus,
            long page,
            long size) {

        Page<BedRecordWithClient> pager = new Page<>(page, size);
        IPage<BedRecordWithClient> result = dao.selectWithClientByCondition(
                pager, clientName, beginTime, endTime, bedRecordStatus
        );
        return new ResponseBean<>(result);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseBean<Void> swapBed(
            Integer oldBedId,
            Integer newBedId,
            Date newBeginTime,
            Date newEndTime
    ) {
        // —— 0. 打印入参 ——
        System.out.println(">>> swapBed called with oldBedId=" + oldBedId
                + ", newBedId=" + newBedId
                + ", newBeginTime=" + newBeginTime
                + ", newEndTime=" + newEndTime);

        // —— 0.1 时间校验 ——
        if (newBeginTime == null || newEndTime == null) {
            System.out.println("!!! 参数中的时间为 null");
            throw new IllegalArgumentException("开始时间和结束时间都不能为空");
        }
        if (newEndTime.before(newBeginTime)) {
            System.out.println("!!! 结束时间早于开始时间: " + newEndTime + " < " + newBeginTime);
            throw new IllegalArgumentException("结束时间不能早于开始时间");
        }

        // —— 1. 查旧记录 ——
        LambdaQueryWrapper<BedRecord> qw = new LambdaQueryWrapper<>();
        qw.eq(BedRecord::getBedId, oldBedId)
                .eq(BedRecord::getBedRecordStatus, 1);
        BedRecord oldRecord = dao.selectOne(qw);
        System.out.println(">>> 查询到的旧记录 oldRecord = " + oldRecord);
        if (oldRecord == null) {
            System.out.println("!!! 没有找到正在使用的旧床位记录 oldBedId=" + oldBedId);
            throw new IllegalArgumentException("找不到正在使用的旧床位记录 oldBedId=" + oldBedId);
        }

        // —— 2. 更新旧记录状态 ——
        oldRecord.setBedRecordStatus(0);
        oldRecord.setBedEndTime(newBeginTime);
        int updOld = dao.updateById(oldRecord);
        System.out.println(">>> 更新旧记录状态，返回影响行数 = " + updOld);

        // —— 3. 更新旧床位状态为“空闲” ——
        Bed oldBed = bedDao.selectById(oldBedId);
        System.out.println(">>> 查询到的旧床位 oldBed = " + oldBed);
        if (oldBed != null) {
            oldBed.setBedStatus("空闲");
            int updBed = bedDao.updateById(oldBed);
            System.out.println(">>> 更新旧床位状态，返回影响行数 = " + updBed);
        }

        // —— 4. 构建并插入新记录 ——
        BedRecord newRecord = new BedRecord();
        newRecord.setClientId(oldRecord.getClientId());
        newRecord.setBedId(newBedId);
        newRecord.setBedBeginTime(newBeginTime);
        newRecord.setBedEndTime(newEndTime);
        newRecord.setBedRecordStatus(1);
        System.out.println(">>> 即将插入新记录 newRecord = " + newRecord);
        int ins = dao.insert(newRecord);
        System.out.println(">>> dao.insert 返回 = " + ins
                + "；插入后 newRecord.id = " + newRecord.getBedRecordId());

        // —— 5. 更新新床位状态为“占用” ——
        Bed newBed = bedDao.selectById(newBedId);
        System.out.println(">>> 查询到的新床位 newBed = " + newBed);
        if (newBed != null) {
            newBed.setBedStatus("有人");
            int updNewBed = bedDao.updateById(newBed);
            int clientId = oldRecord.getClientId();
            Client client = clientDao.selectById(clientId);
            client.setBedId(newBed.getBedId());
            clientDao.updateById(client);
//            System.out.println(">>> 更新新床位状态，返回影响行数 = " + updNewBed);
        }

//        System.out.println("<<< swapBed completed successfully");
        return new ResponseBean<>(200, "床位调换成功");
    }

}
